package com.one.square.oauth.service.impl;

import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.one.square.core.domain.LoginAppUser;
import com.one.square.core.domain.Result;
import com.one.square.oauth.fegin.user.SysUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author cwm
 * @Description 认证服务器加载用户的接口扩展
 * @date 2021/10/28 下午1:25
 * @Version 1.0
 */
@Service
@Slf4j
@AllArgsConstructor
public class OneSquareUserDetailsServiceImpl implements UserDetailsService {
    private final SysUserService sysUserService;

    /**
     * 根据用户名查询用户
     *
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StrUtil.isEmpty(username)) {
            log.warn("用户登陆用户名为空:{}", username);
            throw new UsernameNotFoundException("用户名不能为空");
        }

        Result<LoginAppUser> userResult = sysUserService.findByUsername(username);
        LoginAppUser loginAppUser = userResult.getData();
        if (Objects.isNull(loginAppUser)) {
            log.warn("用户不存在:{}", username);
            throw new UsernameNotFoundException("用户不存在");
        }
        return loginAppUser;
    }

    /**
     * 根据手机号码查询用户
     *
     * @param mobile
     * @return
     */
    public UserDetails loadUserByMobile(String mobile) {
        if (StrUtil.isEmpty(mobile) || PhoneUtil.isMobile(mobile)) {
            log.warn("用户登陆用户手机号码为:{}", mobile);
            throw new UsernameNotFoundException("请输入正确格式的手机号码");
        }
        Result<LoginAppUser> userResult = sysUserService.findByMobile(mobile);
        LoginAppUser loginAppUser = userResult.getData();
        if (Objects.isNull(loginAppUser)) {
            log.warn("用户不存在:{}", mobile);
            throw new UsernameNotFoundException("用户不存在");
        }
        return loginAppUser;
    }
}
